<template>
	<van-popup v-model:show="state.isShow" class="w-full" style="height: 100%" position="right">

		<div class="w-[0] absolute left-[-10px]">
			<ActionSelect ref="typeSelect" v-model:val="form.Type" title="红包类型" :columns="[
				{ text: '等额', value: 2 },
				{ text: '随机', value: 1 }
			]" />
		</div>
		<div class="page">
			<global-header title="发红包" @back="state.isShow = false" />
			<main class="page-main ">
				<van-field label="全部游戏">
					<template #input>
						<div class=" flex-1 row justify-end">
							<van-switch v-model="state.master" :active-value="true" :inactive-value="false" active-color="#3976CC"
								inactive-color="#888" @change="handelMasterSwitch" />
						</div>
					</template>
				</van-field>

				<van-field v-for="item in state.games" :key="item.LotteryId" label-width="80%" :label="item.Name">
					<template #input>
						<div class=" flex-1 row justify-end">
							<van-switch v-model="item.Checked" :active-value="true" :inactive-value="false" active-color="#3976CC"
								inactive-color="#888" @change="handelSubSwitch(item.Checked!, item.LotteryId)" />
						</div>
					</template>
				</van-field>

				<van-cell title="红包类型" :value="form.Type == 2 ? '等额' : '随机'" is-link
					@click="typeSelect.handleShow()"></van-cell>

				<van-field label="指定用户" :model-value="username" disabled></van-field>
				<van-field label="红包积分" v-model="form.Amount" type="digit" input-align="right"></van-field>
				<van-field label="红包数量" :disabled="!!props.username" v-model="form.Count" type="number"
					input-align="right"></van-field>
				<van-field label="最小流水" v-model="form.MiniBet" type="number" input-align="right"></van-field>
				<van-field label="红包备注" v-model="form.Remark" input-align="right"></van-field>

				<van-cell title="到期时间" :value="moment(form.EndTime).format('YYYY-MM-DD HH:mm:ss')" is-link @click="() => {
					date.defaultDate = form.EndTime;
					date.show = true;
				}"></van-cell>

			</main>

			<van-calendar ref="calendarRef" v-model:show="date.show" :default-date="date.defaultDate" type="single"
				@confirm="dateOnConfirm">
				<template #footer>
					<div class="grid grid-cols-2 gap-x-[10px] py-[10px]">
						<van-button size="small" round block @click="date.show = false;">取消</van-button>
						<van-button size="small" type="primary" round block @click="dateOnConfirm"> 确定 </van-button>
					</div>
				</template>
			</van-calendar>

			<div class="p-[15px] bg-[#FFFFFF]">
				<div class="gap-[10px]">
					<van-button @click="confirm()" class="!flex-1 !bg-[#3976CC] !text-[#FFFFFF] rounded-[5px]" block>
						确定
					</van-button>
				</div>
			</div>
		</div>
	</van-popup>
</template>

<script setup lang="ts">
import $bus from "@/utils/bus";
import { debounce } from "lodash-es";
import { useGameStore } from "@/store/modules/game";
import { storeToRefs } from "pinia";
import { reqSendRedPacket, reqUserQuery } from "@/api/user";
import moment from "moment";
import { toast } from "@/utils/toast";

interface FormState {
	GameList: number[];
	Type: number;
	Amount: number;
	Count: number;
	MiniBet: number;
	Remark: string;
	EndTime: any;
}

const calendarRef = ref();
const date = ref({
	show: false,
	defaultDate: new Date(),
})
const dateOnConfirm = () => {
	if (calendarRef.value) {
		const values = calendarRef.value?.getSelectedDate();
		form.EndTime = values;
	}
	date.value.show = false;
}

const typeSelect = ref();

const props = withDefaults(
	defineProps<{
		uid?: number;
		username?: string;
		type: "add" | "edit";
	}>(),
	{}
);
const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
// 获取当前时间
let currentDate = new Date();

// 获取明天的日期
let tomorrowDate = new Date(currentDate);
tomorrowDate.setDate(currentDate.getDate() + 1);

// 将时间设置为零点
tomorrowDate.setHours(0, 0, 0, 0);

const defaultForm = {
	GameList: [],
	Type: 1,
	Amount: null,
	Count: null,
	MiniBet: 0,
	Remark: "恭喜发财！大吉大利！",
	EndTime: tomorrowDate
};
const emit = defineEmits(["update"]);
const state = reactive({
	updating: false,
	isShow: false,
	master: false,
	games: <GameLeftMo[]>[],
	user: "",
	loading: false,
	options: <{ UserId: number; Name: string }[]>[]
});
const form = reactive<FormState>({ ...defaultForm } as any);
const closed = () => {
	state.isShow = false;
	state.master = false;
	reset();
};
const open = () => {
	state.isShow = true;
	initData();
};

const reset = () => {
	form.GameList = [];
	form.Type = 1;
	(form as any).Amount = null;
	(form as any).Count = null;
	form.MiniBet = 0;
	form.Remark = "恭喜发财！大吉大利！";
	form.EndTime = tomorrowDate;

	state.master = false;
	state.games.forEach(item => {
		item.Checked = false;
	});
};

const initData = () => {
	state.games = gameTotal.value.map(item => ({ ...item, Checked: false }));
	if (props.type == "edit") {
	} else {
		(form as any).Count = props.uid ? 1 : null;
		form.Type = 2;
	}
	// 红包报表编辑时
	// if (props.data) {
	//   state.games.forEach(item => {
	//     if (props.data!.lottery_id == item.LotteryId) {
	//       item.Checked = true;
	//     }
	//   });
	//   form.GameList = cloneDeep([props.data!.lottery_id]);
	//   form.Type = props.data!.is_rand;
	//   form.Count = props.data!.Count;
	//   form.MiniBet = +props.data!.min_bet;
	//   form.Remark = props.data!.Remark;
	//   form.EndTime = formatTime(props.data!.ex_time);
	//   form.Amount = +props.data!.Amount;
	// }
};

const handelMasterSwitch = (flag: boolean) => {
	form.GameList = [];
	state.games.forEach(item => {
		item.Checked = flag;
		handelSubSwitch(flag, item.LotteryId);
	});
};

const handelSubSwitch = (flag: boolean, id: number) => {
	if (flag) {
		form.GameList.push(id);
	} else {
		form.GameList = form.GameList.filter(item => item !== id);
	}
};

const remoteMethod = async (query: string) => {
	if (query) {
		state.loading = true;
		const res = await reqUserQuery({
			Name: query
		});
		state.options = res.data;
		state.loading = false;
	} else {
		state.options = [];
	}
};

const confirm = debounce(
	async () => {
		const list = form.GameList.map(num => `{${num}}`).join("");
		if (form.GameList.length == 0) {
			return toast.fail("请选择游戏");
		}
		if (!props.uid && !state.user) {
			return toast.fail("请选择用户");
		}
		if (!form.Amount) {
			return toast.fail("请输入红包积分");
		}
		if (!form.Count) {
			return toast.fail("请输入红包数量");
		}
		if (!form.MiniBet && form.MiniBet !== 0) {
			return toast.fail("请输入最小流水");
		}
		if (!form.EndTime) {
			return toast.fail("请选择到期时间");
		}
		const data = {
			GameList: list,
			Type: form.Type,
			UserId: <number | null>null,
			Amount: Number(form.Amount),
			Count: Number(form.Count),
			MiniBet: Number(form.MiniBet),
			Remark: form.Remark,
			EndTime: moment(form.EndTime).format("YYYY-MM-DD HH:mm:ss")
		};
		if (props.uid) {
			data["UserId"] = props.uid;
		} else {
			data["UserId"] = Number(state.user);
		}
		try {
			state.updating = true;
			await reqSendRedPacket(data);
			state.updating = false;
			state.user = "";
			state.options = [];
			$bus.emit("redpack-send-success");
			emit("update");
			toast.success("发送成功");
			setTimeout(() => {
				closed();
			}, 200);
		} catch (error) {
			state.updating = false;
			console.log(error);
		}
	},
	500,
	{ leading: true, trailing: false }
);

defineExpose({
	open
});
</script>
<style scoped lang="scss"></style>
